{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import create_engine\n",
    "from sqlalchemy.orm import sessionmaker\n",
    "\n",
    "engine = create_engine('sqlite:///:memory:')\n",
    "\n",
    "Session = sessionmaker(bind=engine)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from datetime import datetime\n",
    "\n",
    "from sqlalchemy import Column, Integer, Numeric, String\n",
    "from sqlalchemy.ext.declarative import declarative_base\n",
    "from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method\n",
    "\n",
    "Base = declarative_base()\n",
    "\n",
    "\n",
    "class Cookie(Base):\n",
    "    __tablename__ = 'cookies'\n",
    "\n",
    "    cookie_id = Column(Integer, primary_key=True)\n",
    "    cookie_name = Column(String(50), index=True)\n",
    "    cookie_recipe_url = Column(String(255))\n",
    "    cookie_sku = Column(String(55))\n",
    "    quantity = Column(Integer())\n",
    "    unit_cost = Column(Numeric(12, 2))\n",
    "    \n",
    "    @hybrid_property\n",
    "    def inventory_value(self):\n",
    "        return self.unit_cost * self.quantity\n",
    "    \n",
    "    @hybrid_method\n",
    "    def bake_more(self, min_quantity):\n",
    "        return self.quantity < min_quantity\n",
    "        \n",
    "    def __repr__(self):\n",
    "        return \"Cookie(cookie_name='{self.cookie_name}', \" \\\n",
    "                       \"cookie_recipe_url='{self.cookie_recipe_url}', \" \\\n",
    "                       \"cookie_sku='{self.cookie_sku}', \" \\\n",
    "                       \"quantity={self.quantity}, \" \\\n",
    "                       \"unit_cost={self.unit_cost})\".format(self=self)\n",
    " \n",
    "\n",
    "Base.metadata.create_all(engine)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cookies.unit_cost * cookies.quantity < :param_1\n"
     ]
    }
   ],
   "source": [
    "print(Cookie.inventory_value < 10.00)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cookies.quantity < :quantity_1\n"
     ]
    }
   ],
   "source": [
    "print(Cookie.bake_more(12))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "session = Session()\n",
    "cc_cookie = Cookie(cookie_name='chocolate chip', \n",
    "                   cookie_recipe_url='http://some.aweso.me/cookie/recipe.html', \n",
    "                   cookie_sku='CC01', \n",
    "                   quantity=12, \n",
    "                   unit_cost=0.50)\n",
    "dcc = Cookie(cookie_name='dark chocolate chip',\n",
    "             cookie_recipe_url='http://some.aweso.me/cookie/recipe_dark.html',\n",
    "             cookie_sku='CC02',\n",
    "             quantity=1,\n",
    "             unit_cost=0.75)\n",
    "mol = Cookie(cookie_name='molasses',\n",
    "             cookie_recipe_url='http://some.aweso.me/cookie/recipe_molasses.html',\n",
    "             cookie_sku='MOL01',\n",
    "             quantity=1,\n",
    "             unit_cost=0.80)\n",
    "session.add(cc_cookie)\n",
    "session.add(dcc)\n",
    "session.add(mol)\n",
    "session.flush()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.75"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dcc.inventory_value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dcc.bake_more(12)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      chocolate chip - 6.00\n",
      "            molasses - 0.80\n",
      " dark chocolate chip - 0.75\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/jasomyer/.virtualenvs/sa-book-dev/lib/python2.7/site-packages/sqlalchemy/sql/type_api.py:322: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n",
      "  d[coltype] = rp = d['impl'].result_processor(dialect, coltype)\n"
     ]
    }
   ],
   "source": [
    "from sqlalchemy import desc\n",
    "for cookie in session.query(Cookie).order_by(desc(Cookie.inventory_value)):\n",
    "    print('{:>20} - {:.2f}'.format(cookie.cookie_name, cookie.inventory_value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " dark chocolate chip - 1\n",
      "            molasses - 1\n"
     ]
    }
   ],
   "source": [
    "for cookie in session.query(Cookie).filter(Cookie.bake_more(12)):\n",
    "    print('{:>20} - {}'.format(cookie.cookie_name, cookie.quantity))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
